/**
 * 学生端仪表盘JS
 */
$(document).ready(function() {
    // 获取token
    const token = localStorage.getItem('token');
    if (!token) {
        // 未登录，跳转到登录页
        window.location.href = 'login.html';
        return;
    }

    // 初始化学生信息
    initStudentInfo();
    
    // 初始化学习进度
    initLearningProgress();
    
    // 初始化学科选择器事件
    $('#subject-selector').on('change', function() {
        const subject = $(this).val();
        if (subject) {
            loadExercises(subject);
        }
    });
    
    // 初始化错题本按钮
    $('#mistakes-btn').on('click', function() {
        loadMistakeCollection();
    });
    
    // 初始化能力评估按钮
    $('#assessment-btn').on('click', function() {
        const subject = $('#subject-selector').val();
        if (!subject) {
            showMessage('请先选择学科');
            return;
        }
        loadAbilityAssessment(subject);
    });
    
    // 初始化AI助手按钮
    $('#ai-assistant-btn').on('click', function() {
        const subject = $('#subject-selector').val();
        if (!subject) {
            showMessage('请先选择学科');
            return;
        }
        showAiAssistantDialog(subject);
    });
});

/**
 * 初始化学生信息
 */
function initStudentInfo() {
    $.ajax({
        url: '/api/student/profile',
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(response) {
            $('#student-name').text(response.name);
            $('#student-id').text(response.studentId);
            $('#student-class').text(response.className);
            $('#student-grade').text(response.grade);
        },
        error: function(xhr) {
            console.error('获取学生信息失败', xhr);
            showMessage('获取学生信息失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 初始化学习进度
 */
function initLearningProgress() {
    $.ajax({
        url: '/api/student/learning-progress',
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(data) {
            // 渲染学科进度
            renderSubjectProgress(data.subjectProgress);
            
            // 渲染最近练习数据
            renderRecentPractice(data.recentPractice);
            
            // 渲染知识点掌握情况
            renderKnowledgePoints(data.knowledgePoints);
        },
        error: function(xhr) {
            console.error('获取学习进度失败', xhr);
            showMessage('获取学习进度失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 渲染学科进度
 */
function renderSubjectProgress(subjectProgress) {
    const progressContainer = $('#subject-progress');
    progressContainer.empty();
    
    for (const subject in subjectProgress) {
        const progress = subjectProgress[subject];
        const progressBar = `
            <div class="subject-progress-item">
                <div class="subject-name">${subject}</div>
                <div class="progress">
                    <div class="progress-bar" role="progressbar" style="width: ${progress}%" 
                        aria-valuenow="${progress}" aria-valuemin="0" aria-valuemax="100">
                        ${progress}%
                    </div>
                </div>
            </div>
        `;
        progressContainer.append(progressBar);
    }
}

/**
 * 渲染最近练习数据
 */
function renderRecentPractice(recentPractice) {
    $('#total-sessions').text(recentPractice.totalSessions);
    $('#total-exercises').text(recentPractice.totalExercises);
    $('#correct-rate').text((recentPractice.correctRate * 100).toFixed(1) + '%');
    $('#total-time').text(formatTime(recentPractice.totalTime));
}

/**
 * 渲染知识点掌握情况
 */
function renderKnowledgePoints(knowledgePoints) {
    const kpContainer = $('#knowledge-points');
    kpContainer.empty();
    
    knowledgePoints.forEach(kp => {
        const item = `
            <div class="knowledge-point-item">
                <div class="kp-info">
                    <span class="kp-subject">${kp.subject}</span>
                    <span class="kp-name">${kp.name}</span>
                </div>
                <div class="progress">
                    <div class="progress-bar ${getMasteryColorClass(kp.mastery)}" role="progressbar" 
                        style="width: ${kp.mastery * 100}%" aria-valuenow="${kp.mastery * 100}" 
                        aria-valuemin="0" aria-valuemax="100">
                        ${(kp.mastery * 100).toFixed(1)}%
                    </div>
                </div>
            </div>
        `;
        kpContainer.append(item);
    });
}

/**
 * 加载习题
 */
function loadExercises(subject, knowledgePoint = null) {
    const url = knowledgePoint ? 
        `/api/student/recommended-exercises?subject=${subject}&knowledgePoint=${knowledgePoint}` :
        `/api/student/recommended-exercises?subject=${subject}`;
        
    $.ajax({
        url: url,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(exercises) {
            renderExercises(exercises);
        },
        error: function(xhr) {
            console.error('获取习题失败', xhr);
            showMessage('获取习题失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 渲染习题
 */
function renderExercises(exercises) {
    const container = $('#exercise-container');
    container.empty();
    
    if (exercises.length === 0) {
        container.html('<div class="no-data">暂无习题</div>');
        return;
    }
    
    // 创建练习会话
    const sessionForm = `
        <div class="practice-session-info">
            <h4>练习会话</h4>
            <div class="session-timer">已用时间: <span id="session-time">00:00</span></div>
            <div class="session-progress">
                已完成: <span id="completed-count">0</span> / ${exercises.length}
            </div>
        </div>
        <div class="exercises-list"></div>
        <div class="text-center mt-4">
            <button id="submit-practice" class="btn btn-primary btn-lg">提交练习</button>
        </div>
    `;
    
    container.html(sessionForm);
    
    // 渲染习题列表
    const exercisesList = $('.exercises-list');
    
    exercises.forEach((exercise, index) => {
        const exerciseHtml = renderExerciseItem(exercise, index);
        exercisesList.append(exerciseHtml);
    });
    
    // 开始计时
    startSessionTimer();
    
    // 绑定答案选择事件
    bindAnswerEvents();
    
    // 绑定提交按钮事件
    $('#submit-practice').on('click', function() {
        submitPractice(exercises);
    });
}

/**
 * 渲染单个习题
 */
function renderExerciseItem(exercise, index) {
    const exerciseId = exercise.id;
    let optionsHtml = '';
    
    if (exercise.type === 'multiple-choice') {
        // 选择题
        const options = JSON.parse(exercise.options);
        for (const key in options) {
            optionsHtml += `
                <div class="form-check">
                    <input class="form-check-input" type="radio" name="exercise-${exerciseId}" 
                        id="option-${exerciseId}-${key}" value="${key}" data-exercise-index="${index}">
                    <label class="form-check-label" for="option-${exerciseId}-${key}">
                        ${key}. ${options[key]}
                    </label>
                </div>
            `;
        }
    } else if (exercise.type === 'fill-blank') {
        // 填空题
        optionsHtml = `
            <div class="form-group">
                <input type="text" class="form-control" id="answer-${exerciseId}" 
                    placeholder="请输入答案" data-exercise-index="${index}">
            </div>
        `;
    } else {
        // 简答题
        optionsHtml = `
            <div class="form-group">
                <textarea class="form-control" id="answer-${exerciseId}" rows="3" 
                    placeholder="请输入答案" data-exercise-index="${index}"></textarea>
            </div>
        `;
    }
    
    return `
        <div class="exercise-item card mb-3" id="exercise-${exerciseId}" data-exercise-id="${exerciseId}">
            <div class="card-header">
                <span class="badge ${getDifficultyBadgeClass(exercise.difficulty)}">${exercise.difficulty}</span>
                <span class="badge badge-info">${exercise.type === 'multiple-choice' ? '选择题' : exercise.type === 'fill-blank' ? '填空题' : '简答题'}</span>
                <span class="badge badge-secondary">${exercise.subject}</span>
                <span class="badge badge-light">${exercise.topic || '综合'}</span>
            </div>
            <div class="card-body">
                <h5 class="card-title">第 ${index + 1} 题</h5>
                <div class="exercise-content">${exercise.content}</div>
                <div class="exercise-options mt-3">
                    ${optionsHtml}
                </div>
            </div>
        </div>
    `;
}

/**
 * 开始会话计时器
 */
function startSessionTimer() {
    let seconds = 0;
    window.sessionTimer = setInterval(function() {
        seconds++;
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        $('#session-time').text(
            (minutes < 10 ? '0' : '') + minutes + ':' + 
            (remainingSeconds < 10 ? '0' : '') + remainingSeconds
        );
    }, 1000);
}

/**
 * 绑定答案选择事件
 */
function bindAnswerEvents() {
    // 选择题
    $(document).on('change', '.form-check-input', function() {
        updateCompletedCount();
    });
    
    // 填空题和简答题
    $(document).on('input', '.form-control', function() {
        updateCompletedCount();
    });
}

/**
 * 更新已完成题目数量
 */
function updateCompletedCount() {
    let completed = 0;
    
    // 计算选择题答案
    $('.form-check-input:checked').each(function() {
        completed++;
    });
    
    // 计算填空题和简答题答案
    $('.form-control').each(function() {
        if ($(this).val().trim() !== '') {
            completed++;
        }
    });
    
    // 更新UI
    $('#completed-count').text(completed);
}

/**
 * 提交练习
 */
function submitPractice(exercises) {
    // 收集所有答案
    const answers = [];
    let correctCount = 0;
    
    exercises.forEach((exercise, index) => {
        const exerciseId = exercise.id;
        let answer = null;
        let isCorrect = false;
        
        if (exercise.type === 'multiple-choice') {
            // 选择题
            answer = $(`input[name="exercise-${exerciseId}"]:checked`).val();
            if (answer) {
                isCorrect = (answer === exercise.answer);
                if (isCorrect) correctCount++;
            }
        } else {
            // 填空题或简答题
            answer = $(`#answer-${exerciseId}`).val();
            if (answer) {
                // 对于非选择题，前端不判断正确性，由后端处理
                // 这里简单地认为每道题都不正确
                isCorrect = false;
            }
        }
        
        if (answer) {
            answers.push({
                exerciseId: exerciseId,
                answer: answer,
                isCorrect: isCorrect
            });
        }
    });
    
    // 如果没有答案，提示用户
    if (answers.length === 0) {
        showMessage('请至少完成一道题目');
        return;
    }
    
    // 停止计时
    clearInterval(window.sessionTimer);
    
    // 获取学科和知识点
    const subject = $('#subject-selector').val();
    const knowledgePoint = $('#knowledge-point-selector').val() || '';
    
    // 获取完成时间(秒)
    const completionTimeText = $('#session-time').text();
    const [minutes, seconds] = completionTimeText.split(':').map(Number);
    const completionTime = minutes * 60 + seconds;
    
    // 创建提交数据
    const submissionData = {
        subject: subject,
        knowledgePoint: knowledgePoint,
        correctCount: correctCount,
        totalCount: exercises.length,
        completionTime: completionTime,
        answers: answers
    };
    
    // 提交到服务器
    $.ajax({
        url: '/api/student/submit-practice',
        type: 'POST',
        headers: {
            'Authorization': localStorage.getItem('token'),
            'Content-Type': 'application/json'
        },
        data: JSON.stringify(submissionData),
        success: function(response) {
            showPracticeResult(response, submissionData);
        },
        error: function(xhr) {
            console.error('提交练习失败', xhr);
            showMessage('提交练习失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 显示练习结果
 */
function showPracticeResult(response, submissionData) {
    // 创建结果对话框
    const resultHtml = `
        <div class="modal fade" id="practice-result-modal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">练习结果</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="result-statistics">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-value">${submissionData.correctCount}</div>
                                        <div class="stat-label">正确题数</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-value">${submissionData.totalCount}</div>
                                        <div class="stat-label">总题数</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-value">${((submissionData.correctCount / submissionData.totalCount) * 100).toFixed(1)}%</div>
                                        <div class="stat-label">正确率</div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="stat-item">
                                        <div class="stat-value">${formatTime(submissionData.completionTime)}</div>
                                        <div class="stat-label">完成时间</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="result-analysis mt-4">
                            <h5>分析与建议</h5>
                            <div class="analysis-content">${response.analysis || '暂无分析'}</div>
                        </div>
                        
                        <div class="result-mistakes mt-4">
                            <h5>错题集</h5>
                            <p>本次练习添加了 ${response.mistakesCount || 0} 道错题到错题本</p>
                            <button class="btn btn-outline-primary" id="view-mistakes-btn">
                                查看错题本
                            </button>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" id="new-practice-btn">开始新练习</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    $('body').append(resultHtml);
    
    // 显示对话框
    $('#practice-result-modal').modal('show');
    
    // 绑定按钮事件
    $('#view-mistakes-btn').on('click', function() {
        $('#practice-result-modal').modal('hide');
        loadMistakeCollection();
    });
    
    $('#new-practice-btn').on('click', function() {
        $('#practice-result-modal').modal('hide');
        loadExercises($('#subject-selector').val());
    });
    
    // 对话框关闭后移除
    $('#practice-result-modal').on('hidden.bs.modal', function() {
        $(this).remove();
    });
}

/**
 * 加载错题集
 */
function loadMistakeCollection() {
    const subject = $('#subject-selector').val() || '';
    const url = subject ? 
        `/api/student/mistake-collection?subject=${subject}` :
        '/api/student/mistake-collection';
        
    $.ajax({
        url: url,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(mistakes) {
            renderMistakeCollection(mistakes);
        },
        error: function(xhr) {
            console.error('获取错题集失败', xhr);
            showMessage('获取错题集失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 渲染错题集
 */
function renderMistakeCollection(mistakes) {
    const container = $('#exercise-container');
    container.empty();
    
    if (mistakes.length === 0) {
        container.html('<div class="no-data">暂无错题记录</div>');
        return;
    }
    
    container.html(`
        <div class="mistakes-header">
            <h3>错题本 <span class="badge badge-pill badge-info">${mistakes.length}</span></h3>
            <div class="btn-group">
                <button class="btn btn-outline-secondary" id="back-to-exercises-btn">
                    返回习题练习
                </button>
            </div>
        </div>
        <div class="mistakes-list mt-3"></div>
    `);
    
    const mistakesList = $('.mistakes-list');
    
    mistakes.forEach(mistake => {
        const mistakeHtml = `
            <div class="mistake-item card mb-3" id="mistake-${mistake.id}">
                <div class="card-header">
                    <span class="badge ${getSubjectBadgeClass(mistake.subject)}">${mistake.subject}</span>
                    <span class="badge badge-secondary">${mistake.knowledgePoint || '综合'}</span>
                    <span class="badge badge-info">${mistake.questionType || '未分类'}</span>
                    <span class="badge badge-warning">错误次数: ${mistake.mistakeCount}</span>
                    <button class="btn btn-sm btn-outline-danger float-right remove-mistake-btn" 
                        data-mistake-id="${mistake.id}">
                        移出错题本
                    </button>
                </div>
                <div class="card-body">
                    <div class="mistake-content">${mistake.content}</div>
                    <div class="mistake-answer mt-3">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mistake-student-answer">
                                    <h6>你的答案：</h6>
                                    <div class="answer-content">${mistake.studentAnswer || '未作答'}</div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mistake-correct-answer">
                                    <h6>正确答案：</h6>
                                    <div class="answer-content">${mistake.correctAnswer}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mistake-analysis mt-3">
                        <h6>解析：</h6>
                        <div class="analysis-content">${mistake.analysis || '暂无解析'}</div>
                    </div>
                </div>
            </div>
        `;
        
        mistakesList.append(mistakeHtml);
    });
    
    // 绑定返回按钮事件
    $('#back-to-exercises-btn').on('click', function() {
        const subject = $('#subject-selector').val();
        if (subject) {
            loadExercises(subject);
        } else {
            showMessage('请先选择学科');
        }
    });
    
    // 绑定移出错题本按钮事件
    $('.remove-mistake-btn').on('click', function() {
        const mistakeId = $(this).data('mistake-id');
        removeMistake(mistakeId);
    });
}

/**
 * 移出错题本
 */
function removeMistake(mistakeId) {
    $.ajax({
        url: `/api/student/mistake-collection/${mistakeId}`,
        type: 'DELETE',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function() {
            // 从UI移除
            $(`#mistake-${mistakeId}`).fadeOut(300, function() {
                $(this).remove();
                
                // 检查是否还有错题
                if ($('.mistake-item').length === 0) {
                    $('.mistakes-list').html('<div class="no-data">暂无错题记录</div>');
                }
            });
        },
        error: function(xhr) {
            console.error('移除错题失败', xhr);
            showMessage('移除错题失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 加载能力评估
 */
function loadAbilityAssessment(subject) {
    $.ajax({
        url: `/api/student/ability-assessment?subject=${subject}`,
        type: 'GET',
        headers: {
            'Authorization': localStorage.getItem('token')
        },
        success: function(assessment) {
            renderAbilityAssessment(assessment, subject);
        },
        error: function(xhr) {
            console.error('获取能力评估失败', xhr);
            showMessage('获取能力评估失败: ' + getErrorMessage(xhr));
        }
    });
}

/**
 * 渲染能力评估
 */
function renderAbilityAssessment(assessment, subject) {
    const container = $('#exercise-container');
    container.empty();
    
    container.html(`
        <div class="assessment-header">
            <h3>${subject}学科能力评估</h3>
            <div class="btn-group">
                <button class="btn btn-outline-secondary" id="back-to-exercises-btn">
                    返回习题练习
                </button>
            </div>
        </div>
        <div class="assessment-content mt-3">
            <div class="row">
                <div class="col-md-6">
                    <div class="assessment-radar-chart">
                        <canvas id="radar-chart"></canvas>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="assessment-details"></div>
                </div>
            </div>
            <div class="assessment-summary mt-4"></div>
        </div>
    `);
    
    // 渲染雷达图
    renderRadarChart(assessment.dimensions);
    
    // 渲染评估详情
    renderAssessmentDetails(assessment.dimensions);
    
    // 渲染总结
    $('.assessment-summary').html(`
        <h4>评估总结</h4>
        <div class="card">
            <div class="card-body">
                ${assessment.summary || '暂无评估总结'}
            </div>
        </div>
    `);
    
    // 绑定返回按钮事件
    $('#back-to-exercises-btn').on('click', function() {
        loadExercises(subject);
    });
}

/**
 * 渲染雷达图
 */
function renderRadarChart(dimensions) {
    const labels = [];
    const data = [];
    
    dimensions.forEach(dim => {
        labels.push(dim.name);
        data.push(dim.score);
    });
    
    const ctx = document.getElementById('radar-chart').getContext('2d');
    new Chart(ctx, {
        type: 'radar',
        data: {
            labels: labels,
            datasets: [{
                label: '能力得分',
                data: data,
                backgroundColor: 'rgba(54, 162, 235, 0.2)',
                borderColor: 'rgb(54, 162, 235)',
                pointBackgroundColor: 'rgb(54, 162, 235)',
                pointBorderColor: '#fff',
                pointHoverBackgroundColor: '#fff',
                pointHoverBorderColor: 'rgb(54, 162, 235)'
            }]
        },
        options: {
            scale: {
                ticks: {
                    beginAtZero: true,
                    max: 100
                }
            }
        }
    });
}

/**
 * 渲染评估详情
 */
function renderAssessmentDetails(dimensions) {
    const detailsContainer = $('.assessment-details');
    detailsContainer.empty();
    
    detailsContainer.append('<h4>能力维度详情</h4>');
    
    const table = $(`
        <table class="table">
            <thead>
                <tr>
                    <th>能力维度</th>
                    <th>得分</th>
                    <th>等级</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    `);
    
    const tbody = table.find('tbody');
    
    dimensions.forEach(dim => {
        const level = getScoreLevel(dim.score);
        tbody.append(`
            <tr>
                <td>${dim.name}</td>
                <td>${dim.score}</td>
                <td><span class="badge ${getLevelBadgeClass(level)}">${level}</span></td>
            </tr>
        `);
    });
    
    detailsContainer.append(table);
}

/**
 * 显示AI助手对话框
 */
function showAiAssistantDialog(subject) {
    // 创建对话框
    const dialogHtml = `
        <div class="modal fade" id="ai-assistant-modal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">AI学习助手 - ${subject}</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="ai-loading text-center">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">正在加载...</span>
                            </div>
                            <p>正在分析您的学习情况...</p>
                        </div>
                        <div class="ai-response" style="display: none;"></div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    $('body').append(dialogHtml);
    
    // 显示对话框
    $('#ai-assistant-modal').modal('show');
    
    // 对话框关闭后移除
    $('#ai-assistant-modal').on('hidden.bs.modal', function() {
        $(this).remove();
    });
    
    // 获取AI助手反馈
    $.ajax({
        url: '/api/student/ai-assistant',
        type: 'POST',
        headers: {
            'Authorization': localStorage.getItem('token'),
            'Content-Type': 'application/json'
        },
        data: JSON.stringify({
            subject: subject
        }),
        success: function(response) {
            $('.ai-loading').hide();
            $('.ai-response').html(formatAiResponse(response.analysis)).show();
        },
        error: function(xhr) {
            console.error('获取AI助手反馈失败', xhr);
            $('.ai-loading').hide();
            $('.ai-response').html(`
                <div class="alert alert-danger">
                    获取AI助手反馈失败: ${getErrorMessage(xhr)}
                </div>
            `).show();
        }
    });
}

/**
 * 格式化AI响应
 */
function formatAiResponse(text) {
    if (!text) return '暂无反馈';
    
    // 将换行符转换为<br>
    return text.replace(/\n/g, '<br>');
}

/**
 * 显示提示消息
 */
function showMessage(message, type = 'error') {
    const alertClass = type === 'error' ? 'alert-danger' : 'alert-success';
    
    const alert = $(`
        <div class="alert ${alertClass} alert-dismissible fade show message-alert" role="alert">
            ${message}
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
        </div>
    `);
    
    $('#message-container').append(alert);
    
    // 3秒后自动消失
    setTimeout(function() {
        alert.alert('close');
    }, 3000);
}

/**
 * 格式化时间
 */
function formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const remainingSeconds = seconds % 60;
    
    return (hours > 0 ? hours + '时' : '') + 
           (minutes > 0 ? minutes + '分' : '') + 
           remainingSeconds + '秒';
}

/**
 * 获取错误消息
 */
function getErrorMessage(xhr) {
    if (xhr.responseJSON && xhr.responseJSON.message) {
        return xhr.responseJSON.message;
    }
    return xhr.statusText || '未知错误';
}

/**
 * 获取掌握程度颜色类
 */
function getMasteryColorClass(mastery) {
    if (mastery >= 0.8) return 'bg-success';
    if (mastery >= 0.6) return 'bg-info';
    if (mastery >= 0.4) return 'bg-warning';
    return 'bg-danger';
}

/**
 * 获取难度徽章类
 */
function getDifficultyBadgeClass(difficulty) {
    if (difficulty === '简单') return 'badge-success';
    if (difficulty === '中等') return 'badge-info';
    if (difficulty === '困难') return 'badge-danger';
    return 'badge-secondary';
}

/**
 * 获取学科徽章类
 */
function getSubjectBadgeClass(subject) {
    const subjectMap = {
        '语文': 'badge-primary',
        '数学': 'badge-success',
        '英语': 'badge-info',
        '物理': 'badge-warning',
        '化学': 'badge-danger',
        '生物': 'badge-dark',
        '历史': 'badge-secondary',
        '地理': 'badge-light',
        '政治': 'badge-primary'
    };
    
    return subjectMap[subject] || 'badge-secondary';
}

/**
 * 获取得分等级
 */
function getScoreLevel(score) {
    if (score >= 90) return '优秀';
    if (score >= 80) return '良好';
    if (score >= 70) return '中等';
    if (score >= 60) return '及格';
    return '不及格';
}

/**
 * 获取等级徽章类
 */
function getLevelBadgeClass(level) {
    if (level === '优秀') return 'badge-success';
    if (level === '良好') return 'badge-info';
    if (level === '中等') return 'badge-primary';
    if (level === '及格') return 'badge-warning';
    return 'badge-danger';
} 